package com.jibei.mendo.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.jibei.mendo.MendoApplication;
import com.jibei.mendo.R;
import com.jibei.mendo.bean.ConfigInfoBean;
import com.jibei.mendo.bean.IgnitionInfoBean;
import com.jibei.mendo.bean.MatrixInfoBean;
import com.jibei.mendo.event.Event;
import com.jibei.mendo.utils.Constant;
import com.jibei.mendo.utils.EventBusUtil;
import com.jibei.mendo.utils.ExcelUtil;
import com.jibei.mendo.utils.ThreadPoolUtils;
import com.jibei.mendo.utils.VibratorUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

/**
 * Created by lhl on 2019/9/1.
 */
public class FileAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<String> strings;
    private List<String> dateList;
    private ReadFileListener mReadFileListener;
    public static String BasicInfo;
    private List<IgnitionInfoBean> ignitionInfoList;
    private List<ConfigInfoBean> configInfoLists;
    private List<MatrixInfoBean> matrixInfoBeanList;
    private String itemStr;

    private boolean isReadOverIgnitionInfo = false;
    private boolean isReadOverConfigInfo = false;
    private boolean isReadOverItemInfo = false;
    private boolean isReadOverMatrixInfo = false;

    //用list保存对应位置的viewHolder
    private List<RecyclerView.ViewHolder> viewHolderList = new ArrayList<>();

    public FileAdapter(Context context, List<String> strings,List<String> dateList ,ReadFileListener mReadFileListener) {
        this.mContext = context;
        this.strings = strings;
        this.dateList =dateList;
        this.mReadFileListener = mReadFileListener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_file, viewGroup, false);
        return new FileAdapter.FileViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        viewHolderList.add(viewHolder);

        String string = strings.get(position);
        ((FileAdapter.FileViewHolder) viewHolder).mText.setText(string);
        ((FileViewHolder) viewHolder).mButton.setOnClickListener(v -> {
            ((FileViewHolder) viewHolder).mPBFileRead.setVisibility(View.VISIBLE);
            SPUtils.getInstance().put("isReadOverIgnitionInfo" + position, false);
            SPUtils.getInstance().put("isReadOverConfigInfo" + position, false);
            SPUtils.getInstance().put("isReadOverItemInfo" + position, false);
            SPUtils.getInstance().put("isReadOverMatrixInfo" + position, false);

            ((FileViewHolder) viewHolder).mButton.setClickable(false);
            /*for (RecyclerView.ViewHolder vh : viewHolderList) {
                ((FileViewHolder) vh).mButton.setClickable(false);
            }
            notifyDataSetChanged();*/
            VibratorUtil.getInstance().executeVibrator(mContext, 100);
            ((FileViewHolder) viewHolder).mButton.setBackgroundColor(mContext.getResources().getColor(R.color.yellow));
            ((FileViewHolder) viewHolder).mButton.setText(R.string.reading_file);

            readExcelAndSaveData(viewHolder, position);
        });
        ((FileViewHolder) viewHolder).mFileDate.setText(dateList.get(position));
    }

    private void readExcelAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        ThreadPoolUtils.execute(() -> {
            readConfigInfoAndSaveData(viewHolder, position);
            ((FileViewHolder) viewHolder).mPBFileRead.post(() -> {
                ((FileViewHolder) viewHolder).mPBFileRead.setProgress(20);
            });
            readDeviceIdInfoAndSaveData(viewHolder, position);
            ((FileViewHolder) viewHolder).mPBFileRead.post(() -> {
                ((FileViewHolder) viewHolder).mPBFileRead.setProgress(40);
            });
            readIgnitionInfoAndSaveData(viewHolder, position);
            ((FileViewHolder) viewHolder).mPBFileRead.post(() -> {
                ((FileViewHolder) viewHolder).mPBFileRead.setProgress(60);
            });
            readItemInfoAndSaveData(viewHolder, position);
            ((FileViewHolder) viewHolder).mPBFileRead.post(() -> {
                ((FileViewHolder) viewHolder).mPBFileRead.setProgress(80);
            });
            readMatrixInfoAndSaveData(viewHolder, position);
        });
    }

    /**
     * 读取配置信息
     */
    @SuppressLint("CheckResult")
    private void readConfigInfoAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        Observable.just(0).doOnNext(aLong -> {
            configInfoLists = ExcelUtil.getInstance().readFromExcelConfigInfo(mContext, strings.get(position), 5);
        }).subscribe(aLong -> {
            if (configInfoLists != null && configInfoLists.size() > 0) {
                MendoApplication.getApplication().getDaoSession().getConfigInfoBeanDao().deleteAll();
                MendoApplication.getApplication().getDaoSession().getConfigInfoBeanDao().insertOrReplaceInTx(configInfoLists);
                isReadOverConfigInfo = true;
                changeButtonStatus(viewHolder, position);
            }
        });
    }

    /**
     * 读取基础信息
     */
    @SuppressLint("CheckResult")
    private void readDeviceIdInfoAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        Observable.just(0).doOnNext(aLong -> {
            BasicInfo = ExcelUtil.getInstance().readFromExcelDeviceInfo(mContext, strings.get(position), 1);
        }).subscribe(aLong -> {
            if (BasicInfo != null && BasicInfo.length() > 0) {
                String ID = "";
                String ROLE = "";
                Log.d("lhl","Got info:"+BasicInfo);
                try{
                    String s[] = BasicInfo.split(",");

                    ID = s[0];
                    ROLE = s[1];
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.ID_FROM_EXCEL, ID));
                SPUtils.getInstance().put(Constant.LOCALID,ID);
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.ROLE_FROM_EXCEL, ROLE));
                isReadOverIgnitionInfo = true;
                changeButtonStatus(viewHolder, position);
            }
        });
    }

    /**
     * 读取点火信息
     */
    @SuppressLint("CheckResult")
    private void readIgnitionInfoAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        Observable.just(0).doOnNext(aLong -> {
            ignitionInfoList = ExcelUtil.getInstance().readFromExcelIgnitionInfo(mContext, strings.get(position), 4);
        }).subscribe(aLong -> {
            if (ignitionInfoList != null && ignitionInfoList.size() > 0) {
                MendoApplication.getApplication().getDaoSession().getIgnitionInfoBeanDao().deleteAll();
                MendoApplication.getApplication().getDaoSession().getIgnitionInfoBeanDao().insertOrReplaceInTx(ignitionInfoList);
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.EXCEL_TOTAL_TIMER, ignitionInfoList.get(ignitionInfoList.size() - 1).getTime()));
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.EXCEL_ITEM_NEXT_TIMER, ignitionInfoList.get(0).getTime()));
                isReadOverIgnitionInfo = true;
                changeButtonStatus(viewHolder, position);
            }
        });
    }
    /**
     * 读取Excel某个sheet的最后一行第一列的数据
     */
    @SuppressLint("CheckResult")
    private void readItemInfoAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        Observable.just(0).doOnNext(aLong -> {
            itemStr = ExcelUtil.getInstance().readFromExcelItemInfo(mContext, strings.get(position), 3);
        }).subscribe(aLong -> {
            if (itemStr != null) {
                SPUtils.getInstance().put("sheet2_item", itemStr);
                isReadOverItemInfo = true;
                changeButtonStatus(viewHolder, position);
            }
        });
    }

    /**
     * 读取矩阵信息
     */
    @SuppressLint("CheckResult")
    private void readMatrixInfoAndSaveData(RecyclerView.ViewHolder viewHolder, int position) {
        Observable.just(0).doOnNext(aLong -> {
            matrixInfoBeanList = ExcelUtil.getInstance().readFromExcelMatrixInfo(mContext, strings.get(position), 6);
        }).subscribe(aLong -> {
            if (matrixInfoBeanList != null && matrixInfoBeanList.size() > 0) {
                MendoApplication.getApplication().getDaoSession().getMatrixInfoBeanDao().deleteAll();
                MendoApplication.getApplication().getDaoSession().getMatrixInfoBeanDao().insertOrReplaceInTx(matrixInfoBeanList);
                isReadOverMatrixInfo = true;
                changeButtonStatus(viewHolder, position);
            }
        });
    }

    private synchronized void changeButtonStatus(RecyclerView.ViewHolder viewHolder, int position) {
        if (isReadOverConfigInfo && isReadOverIgnitionInfo && isReadOverItemInfo && isReadOverMatrixInfo) {
            isReadOverIgnitionInfo = false;
            isReadOverConfigInfo = false;
            isReadOverItemInfo = false;
            isReadOverMatrixInfo = false;
            SPUtils.getInstance().put("isReadOverIgnitionInfo" + position, true);
            SPUtils.getInstance().put("isReadOverConfigInfo" + position, true);
            SPUtils.getInstance().put("isReadOverItemInfo" + position, true);
            SPUtils.getInstance().put("isReadOverMatrixInfo" + position, true);

            ((FileViewHolder) viewHolder).mButton.post(() -> {
                ((FileViewHolder) viewHolder).mButton.setClickable(true);
                /*for (RecyclerView.ViewHolder vh : viewHolderList) {
                    ((FileViewHolder) vh).mButton.setClickable(true);
                }
                notifyDataSetChanged();*/

                ((FileViewHolder) viewHolder).mButton.setBackgroundColor(mContext.getResources().getColor(R.color.blue));
                ((FileViewHolder) viewHolder).mButton.setText(R.string.read_file_over);

                ((FileViewHolder) viewHolder).mPBFileRead.setProgress(100);
                ((FileViewHolder) viewHolder).mPBFileRead.setVisibility(View.INVISIBLE);
            });
        }
    }

    @Override
    public int getItemCount() {
        return strings.size();
    }

    private class FileViewHolder extends RecyclerView.ViewHolder {

        private TextView mText;
        private Button mButton;
        private ProgressBar mPBFileRead;
        private TextView mFileDate;

        public FileViewHolder(@NonNull View itemView) {
            super(itemView);
            mText = itemView.findViewById(R.id.tv_file_name);
            mButton = itemView.findViewById(R.id.btn_read_file);
            mPBFileRead = itemView.findViewById(R.id.pb_file_read);
            mFileDate = itemView.findViewById(R.id.tv_file_date);
        }
    }

    public interface ReadFileListener {
        void onReadFileListener(View mView, ProgressBar mProgressBar, int position);
    }
}
